﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SecureDataCMS.Models;
using System.Data.Entity;


namespace SecureDataCMS.Controllers
{
    public class MyProjectsController : Controller
    {
        private SECCMS_liveEntities myDB = new SECCMS_liveEntities();
        const int ADMINISTRATORTYPE = 1;
        const int APPROVERTYPE = 2;
        const int PRIMARYINVTYPE = 3;
        const int DATAMANAGERTYPE = 5;
        const int RESEARCHERTYPE = 4;

        public tblUser LoginCheck(int type) //Function that validates logins. Copypaste between classes.
        {
            HttpCookie logCookie = Request.Cookies["loginCookie"];
            var listOfLogs = myDB.tblLogins.ToList();
            //int validLogin = 0; //invalid to begin with
            tblUser logReturn = null;

            foreach (var log in listOfLogs)
            {
                if (log.LoginKey.ToString().Equals(logCookie.Value) && DateTime.Compare(log.dtmCreated.AddHours(log.intHoursValid), DateTime.Now) >= 0 && log.tblUser.UserTypeID == type) //If their cookie is matching, still valid, and they are an approver
                {
                    //validLogin = 1; //They must be an approver of some kind.
                    logReturn = log.tblUser;
                }

            }
            return logReturn;
        }

        public ActionResult Index()
        {
            HttpCookie theCookie = Request.Cookies["loginCookie"];
            int key = Convert.ToInt32(theCookie.Value);
            tblUser myUser = LoginCheck(PRIMARYINVTYPE);

            bool PI, DM;

            PI = false;
            DM = false;

            if (myUser == null)
            {
                ViewBag.IsPI = false;
                myUser = LoginCheck(DATAMANAGERTYPE);
                if(myUser == null)
                {
                    ViewBag.IsDM = false;
                    myUser = LoginCheck(RESEARCHERTYPE);
                    if(myUser == null)
                    {
                        myUser = LoginCheck(APPROVERTYPE);
                        if (myUser == null)
                        {
                            return Redirect("/");
                        }
                        return Redirect("/MyProjects/ApproverPage");
                    }
                }
                else
                {
                    ViewBag.IsDM = true;
                    DM = true;
                }

            }
            else
            {
                ViewBag.IsPI = true;
                PI = true;
            }

            
            if (PI)
            {
                var PIList = (from T in myDB.tblProjects
                              where T.PI.UserID == myUser.UserID
                              select T);

                ViewBag.PIUserID = myUser.UserID;
                ViewBag.PIList = PIList.ToList();

                var DMList = (from T in myDB.tblProjects
                              where T.intDataManager == myUser.UserID && T.intPrimaryInv != myUser.UserID
                              select T);
                if (DMList.Count() > 0)
                {
                    ViewBag.IsDM = true;
                    ViewBag.DMList = DMList.ToList();
                    ViewBag.DMUserID = myUser.UserID;
                }

            }
            if(DM)
            {
                var DMList = (from T in myDB.tblProjects
                              where T.intDataManager == myUser.UserID && T.intPrimaryInv != myUser.UserID
                              select T);
                if (DMList.Count() > 0)
                {
                    ViewBag.IsDM = true;
                    ViewBag.DMList = DMList.ToList();
                    ViewBag.DMUserID = myUser.UserID;
                }

            }
            var ProjList = (from T in myDB.tblProjects
                            join R in myDB.tblProjectResearchers on T.ProjectID equals R.ProjectID
                            where R.UserID == myUser.UserID
                            select T);

            ViewBag.ProjList = ProjList.ToList();

            ViewBag.UserName = myUser.strFirstName + " " + myUser.strLastName;
            ViewBag.UserID = myUser.UserID;


            return View();
        }

        public ActionResult ApproverPage()
        {
            tblUser myUser = LoginCheck(APPROVERTYPE);

            var ProjList = myDB.GetProjectsForApprover(myUser.UserID);
            

            

            ViewBag.ProjList = ProjList.ToList();

            ViewBag.UserName = myUser.strFirstName + " " + myUser.strLastName;
            ViewBag.UserID = myUser.UserID;

            return View();
        }


        public ActionResult ProjectDetail()
        {
            HttpCookie theCookie = Request.Cookies["loginCookie"];
            int key = Convert.ToInt32(theCookie.Value);
            tblUser myUser = LoginCheck(PRIMARYINVTYPE);

            var ProjectID = Request.QueryString["ID"];
            var intProjectID = Int32.Parse(ProjectID);
            var theProject = (from T in myDB.tblProjects
                               where T.ProjectID == intProjectID
                               select T);

            bool PI, DM;

            PI = false;
            DM = false;
            ViewBag.IsDM = false;

            if (myUser == null)
            {
                ViewBag.IsPI = false;
                myUser = LoginCheck(DATAMANAGERTYPE);
                if (myUser == null)
                {
                    ViewBag.IsDM = false;
                    myUser = LoginCheck(RESEARCHERTYPE);
                    if (myUser == null)
                    {
                        return Redirect("/");
                    }
                }
                else
                {
                    if (myUser.UserID == theProject.First().intDataManager)
                    {
                        ViewBag.IsDM = true;
                    }
                    else
                    {
                        ViewBag.IsDM = false;
                    }
                }

            }
            else
            {
                if (myUser.UserID == theProject.First().intPrimaryInv)
                {
                    ViewBag.IsPI = true;
                }
                else
                {
                    ViewBag.IsPI = false;
                }
            }

            ViewBag.Project = theProject.First() ;

           

            var ProjectUsers = (from T in myDB.tblProjectResearchers
                                  join U in myDB.tblUsers on T.UserID equals U.UserID
                                  where T.ProjectID == intProjectID
                                  select U);

            ViewBag.ProjectUsers = ProjectUsers;

            var targetUsers = myDB.GetPeopleNotInProject(intProjectID);
            var NewUsers = targetUsers.ToList();

            //requests now contains all of the applicable users
            //so we return that to the view which does tihngs with them

            ViewBag.NewUsers = NewUsers;

            
            var projID = Request.QueryString["ID"];
            var intProjID = Int32.Parse(projID);

            //im gonna assume that i have these values in some form
            //this can be changed later once i actually get them

            //aelect from table users where theyre just normal priveleges, (researcher) IDTYPE = 4

            //so where the UID is 4 and where they are not a part of the current project
            //te current projects id were getting fromthe form cause we're assuming that Brock sends it to me


            //inner join 

            //researcher type is un tbl users
            //we need to join tblprjects and tblprojectresearchers
            //so join tbl prijects and users
            //exclude everything where projectresearchers are apart of the project
            //researcher has projectID


            //select from the user table
            //we have the applicable project id already as a variable
            
            //find the researchers whos project id matches the variable project id

            //then get their information from the users table and select that 

            var requests = (from T in myDB.tblUsers
                            join U in myDB.tblProjectResearchers on T.UserID equals U.UserID
                            where U.ProjectID != intProjID
                            select T);

            if (requests.Count() == 0)
                throw new Exception("No matching requests");

            if (requests == null)
            {
                throw new Exception("No matching requests");
            }
            


            //requests now contains all of the applicable users
            //so we return that to the view which does tihngs with them



            ViewBag.ApplicUsers = requests;






            return View();
        }


        public ActionResult DemoteManager()
        {

            var user = Request.Form["dmUserid"];

            ViewBag.userID = user;

            var iuserid = Int32.Parse(user);

            var UserInfoFName = (from W in myDB.tblUsers
                                where W.UserID == iuserid
                                select W.strFirstName
                                );

            var UserInfoLName = (from W in myDB.tblUsers
                                 where W.UserID == iuserid
                                 select W.strLastName
                           );

           var morestuff = UserInfoFName.First();
           var morestuff2 = UserInfoLName.First();

            string userInfoF = morestuff.ToString();

            string userInfoL = morestuff2.ToString();

           
           

            ViewBag.userInfoF = userInfoF;
            ViewBag.userInfoL = userInfoL;


            var projId = Request.Form["dmProjid"];

            int iprojid = Int32.Parse(projId);

            ViewBag.projectID = iprojid;

            

            //find all the users that are in the project


            var ProjectUsers = (from T in myDB.tblProjectResearchers
                                join U in myDB.tblUsers on T.UserID equals U.UserID
                                where T.ProjectID == iprojid
                                select U);

          
            if (ProjectUsers.Count() == 0)
                throw new Exception("No matching requests");

            if (ProjectUsers == null)
            {
                throw new Exception("No matching requests");
            }


            ViewBag.UsersInProj = ProjectUsers;

         

           







            return View();
        }

        public ActionResult performDemote()
        {
            //this function actually performs the demote

            //we get sent the project id and the id of the user were going to promote

            //so go through the datavase and for the current project change the dmid

            //you also need to go through and seee if the person you're demoting is a dm or any other project, if they are then nothing changes
            //otherwise they are removed


            //so we need to get the information of the person we  are promoting


            var projID = Request.Form["dmprojID"];

            var userID = Request.Form["selectDmUser"];
            

            var iprojID = Int32.Parse(projID);



            var iuserid = Int32.Parse(userID);

            var userinf = (from W in myDB.tblUsers
                                 where W.UserID == iuserid
                                 select W
                                );

                        

            var userInfo = userinf.First();

            //userinfo contains the info of the user that we are adding

            //so now we get the info of the datamanaer were demoting

            var dmID = Request.Form["dmdmID"];

            var idmID = Int32.Parse(dmID);

            //so now we have the id of the datamanager

            

            //so now we change the id of the dm in the project into the new person

            //so select the dm in the table


            

            var currdm = ( from E in myDB.tblProjects
                           where E.ProjectID == iprojID
                           select E);

            var stuff  = currdm.First();

            tblProject requests = stuff;

            //now change the dm in currDm

            requests.intDataManager = iuserid;
            
            UpdateModel(requests);
            myDB.SaveChanges();

            //now the dms id in the project has been updated

            //so now we need to change the new dms stuff in the researchers table 

            var userResearcher = (from I in myDB.tblProjectResearchers
                                  where I.UserID == iuserid
                                  select I);

            tblProjectResearcher users = userResearcher.First();


            //userresearcher now contains the info for the current guy

            users.blnIsDM = 1;

            UpdateModel(users);
            myDB.SaveChanges();



            //select from tableprojects where projectid != given proj id and intdatamanager = user
            
            //now to chack if the old dm is the dm for anything else, if he is then nothing changes, otherwise change his account

            //so get the info for the old dm

            //the dm has already been removed from the current project

            var oldDm = (from O in myDB.tblProjects
                         where O.ProjectID != iprojID && O.intDataManager == idmID
                         select O );



            if(oldDm.Count() == 0)
            {

                var changingStuff = (from H in myDB.tblUsers
                                     where H.UserID == idmID
                                     select H);

                tblUser permiss = changingStuff.First();

                permiss.UserTypeID = 4;

                //so now we've changed it 

         
                UpdateModel(permiss);

                myDB.SaveChanges();



                //usertype id changes to researcher




                //then he can be demoted
                //safely so his usertype can be changes


                
            }
            else
            {
                //he stays as a dm so nothing changes


            }

            //now update the database 







           
            return Redirect("/MyProjects/ProjectDetail?ID=" + projID.ToString());




        }




        public ActionResult revokeDM()
        {
            //this method revokes a datamanges access to a project
            //we get the users ID
            //also need the projects id

          
            //this select all of the columns that relate to this user
            //select researcher that is linked to the current projcet 
            //

            
            var projectID = Request.QueryString["ID"];
            var userID = Request.Form["UserID"];
            
            int projID;
            int iuserID;

            tblProjectResearcher request;
            //STEFFFAN FIXX ITTTTTTTTT




            int.TryParse(projectID, out projID);
            int.TryParse(userID, out iuserID);

            var requests = (from r in myDB.tblProjectResearchers
                            where r.UserID == iuserID && r.ProjectID == projID
                            select r);
            //this selects everything in projcet researcher that fits the criteria

            if (requests.Count() == 0)
                throw new Exception("No matching requests");
            else
                request = requests.First();
            //we only want the first one


            var user = request;


            if (user == null)
            {
                return Redirect("/ControlPanel/Admin"); // This should go to an error page. You there! Programmer! Error Page! :)
            }
            //Now we have the job in question. Hooray. And I is the right number :D

            user.blnIsDM = 0;

            UpdateModel(user);
            myDB.SaveChanges();



            return Redirect("/ControlPanel/DataManager");


        }

        public ActionResult DataManagerApprove()
        {
            //this adds a user to be data manager

            //this select all of the columns that relate to this user

            var userID = Request.Form["DmApprovUser"];
            var projectID = Request.Form["DmApprovProj"];
            int projID;
            int iuserID;

            tblProjectResearcher request;
            //STEFFFAN FIXX ITTTTTTTTT




            int.TryParse(projectID, out projID);
            int.TryParse(userID, out iuserID);

            var requests = (from r in myDB.tblProjectResearchers
                            where r.UserID == iuserID && r.ProjectID == projID
                            select r);

            if (requests.Count() == 0)
                throw new Exception("No matching requests");
            else
                request = requests.First();


            var user = request; //BWA HAHAHAHAHA


            if (user == null)
            {
                return Redirect("/ControlPanel/Admin"); // This should go to an error page. You there! Programmer! Error Page! :)
            }
            //Now we have the job in question. Hooray. And I is the right number :D

            user.blnIsDM = 1;

            UpdateModel(user);
            myDB.SaveChanges();



            return Redirect("/ControlPanel/DataManager");


        }

        public ActionResult RevokeAccess()
        {
            //this function revokes a yusers access to the projcet

            //for each user in tblprojectresearcher where their proj id is == to tblproject.id
            //and then null out the record 

            var userID = Request.Form["RevokeAccessUser"];
            var projectID = Request.Form["RevokeAccessProj"];
            var PID = Request.Form["RevokeAccessPID"];
            int projID;
            int iuserID;

            tblProjectResearcher request;
           
            int.TryParse(projectID, out projID);
            int.TryParse(userID, out iuserID);

            var requests = (from r in myDB.tblProjectResearchers
                            where r.UserID == iuserID && r.ProjectID == projID
                            select r);
            
            if (requests.Count() == 0)
                throw new Exception("No matching requests");
            else
                request = requests.First();

            var user = request; //BWA HAHAHAHAHA
            

         


            if (user == null)
            {
                return Redirect("/ControlPanel/Admin"); // This should go to an error page. You there! Programmer! Error Page! :)
            }
            

            //var user contains the users info that we want to remove

            //so then we remove this user from tbl project researches

      




            //now remove the users acces to a porject
            //STEFFFAN WHAT DOES I DOOOO?????????


            myDB.tblProjectResearchers.Remove(user);

            myDB.SaveChanges();


            

            ///MyProjects/ProjectDetail?ID=@item.ProjectID&UID=@ViewBag.PIUserID

            return Redirect("/MyProjects/ProjectDetail?ID=" + projectID.ToString() + "&UID=" + PID.ToString());



        }

        public ActionResult addUserToProj()
        {

            var uID = Request.Form["selectUser"];
            var projid = Request.Form["projID"];
       
            int iuID;
            int iprojid;
          
         
        /*  
         * memberid
         * projectid
         * userid
         * isdm
         * ispi
         * */
            
        //create new table projcet researcher object
            //put in the uid proj id etc

            //mydb.tblroj.add
            //mydb.save

            tblProjectResearcher dbVar = new tblProjectResearcher();

           iprojid = Convert.ToInt32(projid);

           iuID = Convert.ToInt32(uID);



            dbVar.ProjectID = iprojid;
          
            dbVar.UserID = iuID;


            myDB.tblProjectResearchers.Add(dbVar);

            myDB.SaveChanges();

            var myUser = (from T in myDB.tblUsers
                          where T.UserID == iuID
                          select T);
            var user = myUser.First();

            var proj = (from T in myDB.tblProjects
                        where T.ProjectID == iprojid
                        select T);
            var theProj = proj.First();

            string[] lines = { "From: securecms2@polynubstudios.com", "To: " + user.strEmail, "Subject: Added to project " + theProj.strProjectName, "You have been added to the project " + theProj.strProjectName, "." };

            System.IO.File.WriteAllLines(@"C:\inetpub\mailroot\Pickup\email.txt", lines);

            return Redirect("/MyProjects/ProjectDetail?ID=" + projid.ToString());


        }





        


    }
}
